<?php
/*文件处理
*/
namespace tool\core;
class Tool
{
    /**
     * 删除指定目录下所有文件
     */
    public static function deleteFile($path,$type='*.php')
    {
        $path_arr = glob($path.$type);
        array_map('unlink',$path_arr);
    }
    /*删除目录下所有文件及文件夹
    */
    public static function delDirAndFile($dirName,$subdir=true)
    {
        if ($handle = opendir("$dirName"))
        {
            while(false !== ($item = readdir($handle)))
            {
                if($item != "." && $item != "..")
                {
                    if(is_dir("$dirName/$item"))
                    {
                        self::delDirAndFile("$dirName/$item",false);
                    }
                    else
                    {
                        @unlink("$dirName/$item");
                    }
                }
            }
            closedir($handle);
            if(!$subdir)
            {
                @rmdir($dirName);
            }
        }
    }
    /*创建文件*/
    public static function mkFile($path)
    {
        $path = dirname($path);
        !is_dir($path) && mkdir($path, 0755, true);
    }
    /*日志写入接口*/
    public static function writeLog($arr=array(),$type='all')
    {
        $arr = array_merge($_REQUEST,$arr);
        /*当前时间*/
        $now = date('Y-m-d H:i:s');
        /*日志文件路径*/
        $destination = dirname(__FILE__).'/../log/'.$type.'/'.date('Ym').'/'. date('d') . '.log';
        self::mkFile($destination);
        //检测日志文件大小，超过配置大小则备份日志文件重新生成
        if (is_file($destination) && floor(2097152) <= filesize($destination)) 
        {
            rename($destination, dirname($destination) .'/'. $_SERVER['REQUEST_TIME'] . '-' . basename($destination));
        }
        $arr['timestamp'] = $_SERVER['REQUEST_TIME'];
        $arr['server_addr'] = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0';
        $arr['remote_addr'] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
        $arr['method'] = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI';
        $arr['url'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        $str = var_export($arr,true);
        error_log('['.$now."]\r\n".$str."\r\n---------------------------------------------------------------\r\n",3,$destination);
    }
}